<?php
/**
 * Created by PhpStorm.
 * User: eugene
 * Date: 2018/3/15
 * Time: 09:43
 */

namespace App\Repos;


use App\Events\InitUser;
use App\Models\Car;
use App\Models\Friend;
use App\Models\Member;
use App\Models\UserGoldLog;
use App\Models\UserLotteryLog;
use App\Services\FriendService;
use App\Services\ScoreService;
use App\Services\UserInfoService;
use App\Transformers\MemberTransformer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;

class MemberRepo
{
    protected $user, $userInfoService, $memberTransformer, $remoteFollow;

    public function __construct(UserInfoService $userInfoService, MemberTransformer $memberTransformer)
    {
        $this->userInfoService = $userInfoService;
        $this->memberTransformer = $memberTransformer;

    }

    public function find($user)
    {
        if ($user instanceof Member) {
            $this->user = $user;
        } else {
            $this->user = Member::find($user);
        }
        return $this;
    }

    public function info()
    {
        return $this->memberTransformer->singleData($this->user);
    }


    //增加积分
    public function incrementUserCredit($user, $credit)
    {
        if (!$credit)
            return false;
        if (env('APP_DEBUG')) {
            Log::info(sprintf('user score changing for incre: current(%s),incre(%s)', $user->P_credit, $credit));
        }
        return $user->increment('P_credit', (int)$credit);
    }

    //增加金币
    public static function incrementUserGold($user, $credit)
    {
        if (!$credit)
            return false;
        if (env('APP_DEBUG')) {
            Log::info(sprintf('user score changing for incre: current(%s),incre(%s)', $user->P_credit, $credit));
        }
        return $user->increment('P_credit', (int)$credit);
    }

    //减少积分
    public static function decrementUserCredit($user, $credit)
    {
        if (!$credit) return false;
        if (env('APP_DEBUG')) {
            Log::info(sprintf('user score changing for decre: current(%s),decre(%s)', $user->P_credit, $credit));
        }
        return $user->decrement('P_credit', $credit);
    }

    //增加积分
    public function incrementUserRemoteScore($user, $score)
    {
        if (!$score) return false;
        $params = [
            'user_id' => $user->id,
            'operate' => 1,
            'gold_num' => $score,
            'descr' => '增加积分',
        ];
        $new_record = new UserGoldLog();
        $new_record->fill($params);
        $new_record->save();
        if (empty($new_record))
            return false;

        (new ScoreService())->creditsIncre($user->token, $user->remote_user_id, $score, md5($new_record->id));
        return $user->increment('remote_score', (int)$score);
    }

    //增加积分
    public function incrementUserRemoteScoreForSign($user, $score)
    {
        if (!$score) return false;
        $params = [
            'user_id' => $user->id,
            'operate' => 1,
            'gold_num' => $score,
            'descr' => '增加签到积分',
        ];
        $new_record = new UserGoldLog();
        $new_record->fill($params);
        $new_record->save();
        if (empty($new_record))
            return false;

        (new ScoreService())->creditsIncreForSign($user->token, $user->remote_user_id, $score, md5($new_record->id));
        return $user->increment('remote_score', (int)$score);
    }

    //增加积分
    public function incrementUserRemoteScoreForCard($user, $score)
    {
        if (!$score) return false;
        $params = [
            'user_id' => $user->id,
            'operate' => 1,
            'gold_num' => $score,
            'descr' => '增加签到集齐卡片积分',
        ];
        $new_record = new UserGoldLog();
        $new_record->fill($params);
        $new_record->save();
        if (empty($new_record))
            return false;

        (new ScoreService())->creditsIncreCard($user->token, $user->remote_user_id, $score, md5($new_record->id));
        return $user->increment('remote_score', (int)$score);
    }

    //减少积分-未使用
    public function decrementUserRemoteScore($user, $score)
    {
        if (!$score) return false;
        $params = [
            'user_id' => $user->id,
            'operate' => -1,
            'gold_num' => $score,
            'descr' => '减少积分',
        ];
        $new_record = new UserGoldLog();
        $new_record->fill($params);
        $new_record->save();
        if (empty($new_record))
            return false;

        (new UserInfoService())->creditsDecre($user->remote_user_id, $score, $new_record->id);
        return $user->decrement('remote_score', $score);
    }

    public static function checkIsFriend($user_id, $to_user_id)
    {
        $where1 = [
            ['user_id', $user_id],
            ['to_user_id', $to_user_id],
        ];
        return Friend::where($where1)->exists();
    }

    public  static function  findUserForRemote($remote_user_id)
    {
        return Member::where('remote_user_id', $remote_user_id)->first();
    }

    public static function findUser($user_token)
    {
        if (!$user_token) return false;
        $cache_name = 'user_token_' . $user_token;
        $remote_user_id = Cache::get($cache_name);
        if (!$remote_user_id) {
            $user = (new UserInfoService())->getCurrentUser($user_token);

            if (!$user) {
                return false;
            }
            $remote_user_id = $user['user_id'];

            Cache::put($cache_name, $remote_user_id, 1440);//FIXME::优化-将remote_id缓存1天
            if ($member = Member::where('remote_user_id', $remote_user_id)->first()) {
                $member->nickname = $user['nickname'];
                $member->avatar = $user['avatar'];
                $member->token = $user_token;
                $member->save();
                return $member;
            }

            $new_user = new Member();
            $new_user->nickname = $user['nickname'];
            $new_user->avatar = $user['avatar'];
            $new_user->token = $user_token;
            $new_user->remote_user_id = $remote_user_id;
            $new_user->level = 2;
            $new_user->P_credit = config('car.cfgStopLimit.GoldForNewUser');
            $new_user->save();

            $lottery_log = new UserLotteryLog();
            $lottery_log->user_id = $new_user->id;
            $lottery_log->lottery_id = 0;
            $lottery_log->gold_num = 0;
            $lottery_log->save();

            //为新用户添加初始礼物
            $new_car_config = config('car.cfgStopLimit.CarForNewUser');
            event(new InitUser($new_user, $new_car_config));

            return Member::where('remote_user_id', $remote_user_id)->first();
        }

        if ($member = Member::where('remote_user_id', $remote_user_id)->first()) {
            return $member;
        }
        return false;
    }

    public function setRemoteFollow()
    {
        $this->remoteFollow = true;
        return $this;
    }


    public function friendsList($user_id, $limit = 5)
    {
        //FIXME::访问随机优化
        $rand = random_int(0, 5);
        if ($rand === 1) {
            //先拉取远程关系同步到应用内
            $user_token = Member::where('uid', $user_id)->value('token');

            if ($this->remoteFollow && config('car.api_config.remote_follow_switch')) {
                $remote_followers = (new FriendService($user_token))->followers();

                if (!empty($remote_followers)) {
                    Friend::where('user_id', $user_id)->delete();
                    foreach ($remote_followers as $follower) {
                        //先全部删除，再添加已有的
                        $to_user_id = Member::where('remote_user_id', $follower)->value('uid');
                        if ($to_user_id && !self::checkIsFriend($user_id, $to_user_id)) {
                            Friend::insert([
                                'user_id' => $user_id,
                                'to_user_id' => $to_user_id,
                            ]);
                        }
                    }
                }
            }
        }

        //获取好友列表
        $uids = Friend::where('user_id', $user_id)->orderByDesc('id')->paginate($limit);

        return $uids->transform(function ($item) {

            return $this->memberTransformer->setTransformer('forSimple')->singleData(Member::find($item['to_user_id']));
        });
    }

    public function randomStrangerUsers($user_id, $limit = 10)
    {

        $uids = Friend::where('user_id', $user_id)->pluck('to_user_id');

        $users = Member::whereNotIn('uid', $uids)->where('uid', '<>', $user_id)->inRandomOrder()->take($limit)->get();

        return $this->memberTransformer->setTransformer('forStranger')->listData($users);
    }

    public function addFriend($user_id, $to_user_id)
    {
        if (!$user_id || !$to_user_id) return false;
        if (!self::checkIsFriend($user_id, $to_user_id)) {

            if (config('car.api_config.remote_follow_switch')) {
                //添加远程关注关系
                $user_token = Member::where('uid', $user_id)->value('token');
                $remote_user_id = Member::where('uid', $to_user_id)->value('remote_user_id');
                (new FriendService($user_token))->follow($remote_user_id);
            }

            return Friend::insert([
                'user_id' => $user_id,
                'to_user_id' => $to_user_id,
            ]);
        }
    }


    //全球排名
    public static function countGlobalRank($credit)
    {
        return Member::where('P_credit', '>=', $credit)->count();
    }


}